﻿/*
 
Celerity: Sensory Overload
Copright 2012 by Adam Hill, David Gannon, Thomas Tamblyn & Patrick Ytting
Contact: adam.hill@outlook.com
Website: adamhill.org
Licence: MS-Pl Licence
  
 */

using Celerity.Data;
using Microsoft.Xna.Framework;

namespace Celerity
{
    public partial class CelerityGame : Game
    {
        int msSinceCVCall = 0;

        protected override void Update(GameTime gameTime)
        {
            // Base & Stats
            base.Update(gameTime);
            int elapsedMilliseconds = gameTime.ElapsedGameTime.Milliseconds;

            // Read Input & Sensors
            NewCVCall(elapsedMilliseconds);
            input.Update();
            if (input.HasUnprocessedExit)
            {
                this.Exit();
            }

            // Game State Changes
            CheckWebcamStatus();

            // Logic
            logic.Update(gameTime, elapsedMilliseconds);

            // Update Modules & Layers
            world.Update(gameTime, HeadPos, logic.ChaosFactor);
            ui.Update(elapsedMilliseconds,
                input.Interactions,
                input.MouseState,
                FramesCaptured,
                FaceCentrePercentX,
                FaceCentrePercentY,
                FaceSizePercentWidth,
                FaceSizePercentHeight);
            audio.Update(logic.ChaosFactor);
        }

        void NewCVCall(int elapsedMilliseconds)
        {
            msSinceCVCall += elapsedMilliseconds;
            int webcamPollDelayMs = GlobalGameStates.CameraState == CameraState.FullFPS ? CeleritySettings.CameraPollDelayFullFPS : CeleritySettings.CameraPollDelayLowFPS;
            if (msSinceCVCall > webcamPollDelayMs)
            {
                msSinceCVCall = 0;
                cv.Update(elapsedMilliseconds);
            }

            this.FramesCaptured = cv.FramesCaptured;
            this.IsFaceDetected = cv.IsFaceDetected;
            this.IsWebcamWorking = cv.IsWebcamWorking;
            this.FaceEllipse = cv.FaceEllipse;
            this.HeadPos = cv.HeadPos;
            this.FaceCentrePercentX = cv.FaceCentrePercentX;
            this.FaceCentrePercentY = cv.FaceCentrePercentY;
            this.FaceSizePercentWidth = cv.FaceSizePercentWidth;
            this.FaceSizePercentHeight = cv.FaceSizePercentHeight;
        }

        void CheckWebcamStatus()
        {
            //Input Pseudo-Events
            if (wasWebcamWorking != IsWebcamWorking)
            {
                // Update status
                wasWebcamWorking = IsWebcamWorking;
                if (IsWebcamWorking)
                {
                    GlobalGameStates.CameraState = CameraState.Override;
                }
            }
        }
    }
}
